package com.yhb.channel.utils;

import com.yhb.channel.ChannelConstant;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.log4j.Log4j;

import java.util.Map;
import java.util.HashMap;

@EqualsAndHashCode(callSuper = true)
@Data
class ChannelJSONException extends RuntimeException {
    private Long code;
    private String message;
    private Throwable nestedException;

    ChannelJSONException(Long code, String message, Throwable nestedException) {
        super(nestedException);
        this.code = code;
        this.message = message;
        this.nestedException = nestedException;
    }
}

@Log4j
public class ChannelJSONUtil {
    public static <T> T parseJson(String json, Class<T> cls) {
        try {
            log.info("JSON parse:" + json);
            return ObjectMapperFactory.getObjectMapper().readValue(json, cls);
        } catch (Throwable t) {
            log.info("通道Json解析出错，源字符串：" + json, t);
            throw new ChannelJSONException(ChannelConstant.ERROR_JSON_WRONG, "通道json解析出错", t);
        }
    }

    public static <T> T parseJson(Map map, Class<T> cls) {
        try {
            log.info("JSON parse map:" + ChannelJSONUtil.toJson(map));
            return ObjectMapperFactory.getObjectMapper().convertValue(map, cls);
        } catch (Throwable t) {
            log.info("通道Json解析出错，源map：" + map, t);
            throw new ChannelJSONException(ChannelConstant.ERROR_JSON_WRONG, "通道json解析出错", t);
        }
    }

    public static String toJson(Object obj) {
        try {
            return ObjectMapperFactory.getObjectMapper().writeValueAsString(obj);
        } catch (Throwable t) {
            log.info("通道Json序列化出错：", t);
            throw new ChannelJSONException(ChannelConstant.ERROR_JSON_WRONG, "通道json序列化出错", t);
        }
    }

    /**
     * 将<String, String>形式的json转化为HashMap
     * @param json 要求是<String, String>形式
     */
    public static HashMap<String, String> jsonToMap(String json) {
        try {
            log.info("JSON parse to map:" + json);
            return ObjectMapperFactory.getObjectMapper().readValue(json, HashMap.class);
        } catch (Throwable t) {
            log.info("通道Json解析出错，源字符串：" + json, t);
            throw new ChannelJSONException(ChannelConstant.ERROR_JSON_WRONG, "通道json解析出错", t);
        }
    }
}
